<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 用户管理</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 用户管理页面 -->
            <div id="users" class="content-page active">
                <div class="page-header">
                    <h2>用户管理</h2>
                    <div class="header-actions">
                        <button class="btn btn-success" onclick="exportUsers()" data-permission="user:export">
                            <i class="fas fa-download"></i>
                            导出Excel
                        </button>
                        <button class="btn btn-info" onclick="downloadImportTemplate()" data-permission="user:import">
                            <i class="fas fa-file-excel"></i>
                            下载模板
                        </button>
                        <button class="btn btn-warning" onclick="showImportModal()" data-permission="user:import">
                            <i class="fas fa-upload"></i>
                            导入Excel
                        </button>
                        <button class="btn btn-secondary" onclick="showReadersPage()" data-permission="user:view">
                            <i class="fas fa-users"></i>
                            读者查询
                        </button>
                        <button class="btn btn-primary" onclick="showAddUserModal()" data-permission="user:create">
                            <i class="fas fa-plus"></i>
                            添加用户
                        </button>
                    </div>
                </div>
                <div class="page-filters">
                    <div class="filter-group">
                        <input type="text" id="userSearch" placeholder="搜索用户..." class="form-control">
                        <select id="userRoleFilter" class="form-control">
                            <option value="">所有角色</option>
                            <option value="system_admin">系统管理员</option>
                            <option value="book_admin">图书管理员</option>
                            <option value="normal_user">普通用户</option>
                        </select>
                        <select id="userStatusFilter" class="form-control">
                            <option value="">所有状态</option>
                            <option value="active">正常</option>
                            <option value="inactive">禁用</option>
                        </select>
                        <button class="btn btn-secondary" onclick="searchUsers()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                        <button class="btn btn-outline-secondary" onclick="resetFilters()">
                            <i class="fas fa-undo"></i>
                            重置
                        </button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>真实姓名</th>
                                <th>角色</th>
                                <th>电话</th>
                                <th>邮箱</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="userTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="userPagination">
                </div>
                <div class="pagination-tools" id="userPaginationTools"></div>
            </div>

            <!-- 读者查询页面 -->
            <div id="readers" class="content-page">
                <div class="page-header">
                    <h2>读者查询</h2>
                    <div class="header-actions">
                        <button class="btn btn-success" onclick="exportReaders()">
                            <i class="fas fa-download"></i>
                            导出读者
                        </button>
                        <button class="btn btn-secondary" onclick="showUsersPage()">
                            <i class="fas fa-arrow-left"></i>
                            返回用户管理
                        </button>
                    </div>
                </div>
                <div class="page-filters">
                    <div class="filter-group">
                        <input type="text" id="readerSearch" placeholder="搜索读者..." class="form-control">
                        <button class="btn btn-secondary" onclick="searchReaders()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                        <button class="btn btn-outline-secondary" onclick="resetReaderFilters()">
                            <i class="fas fa-undo"></i>
                            重置
                        </button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>真实姓名</th>
                                <th>电话</th>
                                <th>邮箱</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="readerTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="readerPagination">
                </div>
                <div class="pagination-tools" id="readerPaginationTools"></div>
            </div>
        </main>
    </div>

    <!-- 模态框 -->
    <div id="modalOverlay" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 id="modalTitle">标题</h3>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
            </div>
            <div class="modal-footer" id="modalFooter">
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script>
        // API基础配置
        const API_BASE_URL = 'http://118.31.223.190:8080';

        // 通用API请求函数
        class ApiClient {
            constructor() {
                this.baseURL = API_BASE_URL;
            }

            async request(url, options = {}) {
                const isForm = options && options.body instanceof FormData;
                const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
                const config = { headers, ...options };

                try {
                    const response = await fetch(`${this.baseURL}${url}`, config);
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    return data;
                } catch (error) {
                    console.error('API请求失败:', error);
                    throw error;
                }
            }

            async get(url, params = {}) {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = queryString ? `${url}?${queryString}` : url;
                return this.request(fullUrl, { method: 'GET' });
            }

            async post(url, data = {}) {
                if (data instanceof FormData) {
                    return this.request(url, { method: 'POST', body: data });
                }
                return this.request(url, { method: 'POST', body: JSON.stringify(data) });
            }

            async put(url, data = {}) {
                return this.request(url, {
                    method: 'PUT',
                    body: JSON.stringify(data)
                });
            }

            async delete(url) {
                return this.request(url, { method: 'DELETE' });
            }
        }

        // 创建API客户端实例
        const api = new ApiClient();

        // 用户管理API
        const UserAPI = {
            // 创建用户
            createUser: (userData) => api.post('/api/users', userData),
            
            // 更新用户
            updateUser: (userData) => api.put('/api/users', userData),
            
            // 删除用户
            deleteUser: (userId) => api.delete(`/api/users/${userId}`),
            
            // 获取用户详情
            getUserById: (userId) => api.get(`/api/users/${userId}`),
            
            // 分页查询用户
            pageUsers: (page = 1, size = 10, keyword = '', role = '', status = '') => 
                api.get('/api/users/page', { page, size, keyword, role, status }),
            
            // 重置密码
            resetPassword: (userId) => api.put(`/api/users/reset-password/${userId}`),
            
            // 导出用户数据
            exportUsers: (keyword = '') => {
                const params = new URLSearchParams();
                if (keyword) params.append('keyword', keyword);
                window.open(`${API_BASE_URL}/api/users/export?${params.toString()}`, '_blank');
            },
            
            // 下载导入模板
            downloadImportTemplate: () => {
                window.open(`${API_BASE_URL}/api/users/import-template`, '_blank');
            },
            
            // 导入用户数据
            importUsers: (file) => {
                const formData = new FormData();
                formData.append('file', file);
                return api.post('/api/users/import', formData);
            },
            
            // 分页查询读者
            pageReaders: (page = 1, size = 10, keyword = '') => 
                api.get('/api/users/readers/page', { page, size, keyword }),
            
            // 获取所有读者
            getAllReaders: (keyword = '') => 
                api.get('/api/users/readers/all', { keyword }),
            
            // 导出读者数据
            exportReaders: (keyword = '') => {
                const params = new URLSearchParams();
                if (keyword) params.append('keyword', keyword);
                window.open(`${API_BASE_URL}/api/users/readers/export?${params.toString()}`, '_blank');
            }
        };

        // 工具函数
        const Utils = {
            // 显示加载状态
            showLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.add('active');
                }
            },

            // 隐藏加载状态
            hideLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.remove('active');
                }
            },

            // 显示消息提示
            showMessage: (message, type = 'info', duration = 3000) => {
                const messageContainer = document.getElementById('messageContainer');
                if (!messageContainer) return;

                const messageEl = document.createElement('div');
                messageEl.className = `message ${type}`;
                
                const iconMap = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle'
                };

                messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                messageContainer.appendChild(messageEl);

                // 自动移除消息
                setTimeout(() => {
                    if (messageEl.parentElement) {
                        messageEl.remove();
                    }
                }, duration);
            },

            // 格式化日期
            formatDate: (dateString) => {
                if (!dateString) return '-';
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            },

            // 获取角色文本
            getRoleText: (role) => {
                const roleMap = {
                    'system_admin': '系统管理员',
                    'book_admin': '图书管理员',
                    'normal_user': '普通用户'
                };
                return roleMap[role] || role;
            },

            // 创建分页组件
            createPagination: (currentPage, totalPages, onPageChange) => {
                const pagination = document.createElement('div');
                pagination.className = 'pagination';

                // 上一页按钮
                const prevBtn = document.createElement('button');
                prevBtn.textContent = '上一页';
                prevBtn.disabled = currentPage <= 1;
                prevBtn.onclick = () => onPageChange(currentPage - 1);
                pagination.appendChild(prevBtn);

                // 页码按钮
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, currentPage + 2);

                if (startPage > 1) {
                    const firstBtn = document.createElement('button');
                    firstBtn.textContent = '1';
                    firstBtn.onclick = () => onPageChange(1);
                    pagination.appendChild(firstBtn);

                    if (startPage > 2) {
                        const ellipsis = document.createElement('span');
                        ellipsis.textContent = '...';
                        ellipsis.style.padding = '0.5rem';
                        pagination.appendChild(ellipsis);
                    }
                }

                for (let i = startPage; i <= endPage; i++) {
                    const pageBtn = document.createElement('button');
                    pageBtn.textContent = i;
                    pageBtn.className = i === currentPage ? 'active' : '';
                    pageBtn.onclick = () => onPageChange(i);
                    pagination.appendChild(pageBtn);
                }

                if (endPage < totalPages) {
                    if (endPage < totalPages - 1) {
                        const ellipsis = document.createElement('span');
                        ellipsis.textContent = '...';
                        ellipsis.style.padding = '0.5rem';
                        pagination.appendChild(ellipsis);
                    }

                    const lastBtn = document.createElement('button');
                    lastBtn.textContent = totalPages;
                    lastBtn.onclick = () => onPageChange(totalPages);
                    pagination.appendChild(lastBtn);
                }

                // 下一页按钮
                const nextBtn = document.createElement('button');
                nextBtn.textContent = '下一页';
                nextBtn.disabled = currentPage >= totalPages;
                nextBtn.onclick = () => onPageChange(currentPage + 1);
                pagination.appendChild(nextBtn);

                return pagination;
            }
        };

        // 全局变量
        let currentUser = null;
        let currentPageNum = 1;
        let currentPageSize = 10;
        let currentView = 'users'; // 'users' 或 'readers'
        let readerPageNum = 1;
        let readerPageSize = 10;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
        });

        // 初始化应用
        function initializeApp() {
            // 使用通用权限检查
            if (!initializePagePermission()) {
                return;
            }
            
            currentUser = authManager.getCurrentUser();
            
            // 生成动态菜单
            generateSidebarMenu();
            
            // 更新用户信息
            document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
            
            // 应用权限控制
            authManager.applyPermissionControl();
            
            // 加载用户数据
            loadUsers();
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 检查登录状态（保留兼容性）
        function checkLoginStatus() {
            return authManager.isLoggedIn();
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            authManager.logout();
            Utils.showMessage('已退出登录', 'info');
        }

        // 显示通知
        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载用户数据
        async function loadUsers(page = 1) {
            try {
                Utils.showLoading();
                
                const keyword = document.getElementById('userSearch')?.value || '';
                const role = document.getElementById('userRoleFilter')?.value || '';
                const status = document.getElementById('userStatusFilter')?.value || '';
                
                const response = await UserAPI.pageUsers(page, currentPageSize, keyword, role, status);
                
                if (response.result === 'SUCCESS') {
                    renderUserTable(response.data.records);
                    const totalPages = Math.max(1, (response.data && response.data.pages) ? response.data.pages : 1);
                    renderPagination('userPagination', page, totalPages, loadUsers);
                    renderPaginationTools('userPaginationTools', totalPages,
                        (n) => { currentPageNum = n; loadUsers(n); },
                        (size) => { currentPageSize = size; currentPageNum = 1; loadUsers(1); }
                    );
                } else {
                    Utils.showMessage(response.message || '加载用户数据失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('加载用户数据失败', 'error');
                console.error('Users load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 渲染用户表格
        function renderUserTable(users) {
            const tbody = document.getElementById('userTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = users.map(user => `
                <tr>
                    <td>${user.userId}</td>
                    <td>${user.username}</td>
                    <td>${user.realName}</td>
                    <td>${Utils.getRoleText(user.role)}</td>
                    <td>${user.phone || '-'}</td>
                    <td>${user.email || '-'}</td>
                    <td><span class="status-badge status-${user.status === 'active' ? 'active' : 'inactive'}">${user.status === 'active' ? '正常' : '禁用'}</span></td>
                    <td>${Utils.formatDate(user.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editUser(${user.userId})" data-permission="user:update">编辑</button>
                        <button class="btn btn-sm btn-warning" onclick="resetUserPassword(${user.userId})" data-permission="user:update">重置密码</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.userId})" data-permission="user:delete">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 搜索用户
        function searchUsers() {
            currentPageNum = 1;
            loadUsers(1);
        }

        // 重置过滤器
        function resetFilters() {
            document.getElementById('userSearch').value = '';
            document.getElementById('userRoleFilter').value = '';
            document.getElementById('userStatusFilter').value = '';
            currentPageNum = 1;
            loadUsers(1);
        }

        // 导出用户数据
        function exportUsers() {
            const keyword = document.getElementById('userSearch')?.value || '';
            UserAPI.exportUsers(keyword);
            Utils.showMessage('正在导出用户数据...', 'info');
        }

        // 下载导入模板
        function downloadImportTemplate() {
            UserAPI.downloadImportTemplate();
            Utils.showMessage('正在下载导入模板...', 'info');
        }

        // 显示导入模态框
        function showImportModal() {
            showModal('导入用户数据', `
                <div class="form-group">
                    <label for="importFile">选择Excel文件</label>
                    <input type="file" id="importFile" accept=".xlsx,.xls" class="form-control">
                    <small class="form-text text-muted">
                        支持.xlsx和.xls格式，请先下载模板了解数据格式要求
                    </small>
                </div>
                <div class="alert alert-info">
                    <h6>导入说明：</h6>
                    <ul>
                        <li>用户名、密码、真实姓名、角色为必填项</li>
                        <li>角色值：system_admin（系统管理员）、book_admin（图书管理员）、normal_user（普通用户）</li>
                        <li>状态值：active（正常）、inactive（禁用），默认为active</li>
                        <li>手机号格式：1开头的11位数字</li>
                        <li>邮箱格式：标准邮箱格式</li>
                    </ul>
                </div>
            `, `
                <button class="btn btn-primary" onclick="submitImportUsers()">导入</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
        }

        // 提交导入用户
        async function submitImportUsers() {
            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];
            
            if (!file) {
                Utils.showMessage('请选择要导入的文件', 'warning');
                return;
            }
            
            try {
                Utils.showLoading();
                const response = await UserAPI.importUsers(file);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage(response.data, 'success');
                    closeModal();
                    loadUsers();
                } else {
                    Utils.showMessage(response.message || '导入失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '导入失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示读者页面
        function showReadersPage() {
            document.getElementById('users').classList.remove('active');
            document.getElementById('readers').classList.add('active');
            currentView = 'readers';
            loadReaders();
        }

        // 显示用户页面
        function showUsersPage() {
            document.getElementById('readers').classList.remove('active');
            document.getElementById('users').classList.add('active');
            currentView = 'users';
            loadUsers();
        }

        // 加载读者数据
        async function loadReaders(page = 1) {
            try {
                Utils.showLoading();
                
                const keyword = document.getElementById('readerSearch')?.value || '';
                
                const response = await UserAPI.pageReaders(page, readerPageSize, keyword);
                
                if (response.result === 'SUCCESS') {
                    renderReaderTable(response.data.records);
                    const totalPages = Math.max(1, (response.data && response.data.pages) ? response.data.pages : 1);
                    renderPagination('readerPagination', page, totalPages, loadReaders);
                    renderPaginationTools('readerPaginationTools', totalPages,
                        (n) => { readerPageNum = n; loadReaders(n); },
                        (size) => { readerPageSize = size; readerPageNum = 1; loadReaders(1); }
                    );
                } else {
                    Utils.showMessage(response.message || '加载读者数据失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('加载读者数据失败', 'error');
                console.error('Readers load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 渲染读者表格
        function renderReaderTable(readers) {
            const tbody = document.getElementById('readerTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = readers.map(reader => `
                <tr>
                    <td>${reader.userId}</td>
                    <td>${reader.username}</td>
                    <td>${reader.realName}</td>
                    <td>${reader.phone || '-'}</td>
                    <td>${reader.email || '-'}</td>
                    <td><span class="status-badge status-${reader.status === 'active' ? 'active' : 'inactive'}">${reader.status === 'active' ? '正常' : '禁用'}</span></td>
                    <td>${Utils.formatDate(reader.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="viewReaderDetail(${reader.userId})">详情</button>
                        <button class="btn btn-sm btn-primary" onclick="editUser(${reader.userId})">编辑</button>
                        <button class="btn btn-sm btn-warning" onclick="resetUserPassword(${reader.userId})">重置密码</button>
                    </td>
                </tr>
            `).join('');
        }

        // 搜索读者
        function searchReaders() {
            readerPageNum = 1;
            loadReaders(1);
        }

        // 重置读者过滤器
        function resetReaderFilters() {
            document.getElementById('readerSearch').value = '';
            readerPageNum = 1;
            loadReaders(1);
        }

        // 导出读者数据
        function exportReaders() {
            const keyword = document.getElementById('readerSearch')?.value || '';
            UserAPI.exportReaders(keyword);
            Utils.showMessage('正在导出读者数据...', 'info');
        }

        // 查看读者详情
        async function viewReaderDetail(userId) {
            try {
                Utils.showLoading();
                const response = await UserAPI.getUserById(userId);
                
                if (response.result === 'SUCCESS') {
                    const reader = response.data;
                    showModal('读者详情', `
                        <div class="reader-detail">
                            <div class="detail-row">
                                <label>用户ID：</label>
                                <span>${reader.userId}</span>
                            </div>
                            <div class="detail-row">
                                <label>用户名：</label>
                                <span>${reader.username}</span>
                            </div>
                            <div class="detail-row">
                                <label>真实姓名：</label>
                                <span>${reader.realName}</span>
                            </div>
                            <div class="detail-row">
                                <label>角色：</label>
                                <span>${Utils.getRoleText(reader.role)}</span>
                            </div>
                            <div class="detail-row">
                                <label>联系电话：</label>
                                <span>${reader.phone || '-'}</span>
                            </div>
                            <div class="detail-row">
                                <label>邮箱：</label>
                                <span>${reader.email || '-'}</span>
                            </div>
                            <div class="detail-row">
                                <label>状态：</label>
                                <span class="status-badge status-${reader.status === 'active' ? 'active' : 'inactive'}">${reader.status === 'active' ? '正常' : '禁用'}</span>
                            </div>
                            <div class="detail-row">
                                <label>创建时间：</label>
                                <span>${Utils.formatDate(reader.createTime)}</span>
                            </div>
                        </div>
                    `, `
                        <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    `);
                } else {
                    Utils.showMessage(response.message || '获取读者信息失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '获取读者信息失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示添加用户模态框
        function showAddUserModal() {
            showModal('添加用户', `
                <form id="addUserForm">
                    <div class="form-group">
                        <label for="addUsername">用户名</label>
                        <input type="text" id="addUsername" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="addPassword">密码</label>
                        <input type="password" id="addPassword" name="password" required>
                    </div>
                    <div class="form-group">
                        <label for="addRealName">真实姓名</label>
                        <input type="text" id="addRealName" name="realName" required>
                    </div>
                    <div class="form-group">
                        <label for="addRole">角色</label>
                        <select id="addRole" name="role" required>
                            <option value="normal_user">普通用户</option>
                            <option value="book_admin">图书管理员</option>
                            <option value="system_admin">系统管理员</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="addPhone">电话</label>
                        <input type="tel" id="addPhone" name="phone">
                    </div>
                    <div class="form-group">
                        <label for="addEmail">邮箱</label>
                        <input type="email" id="addEmail" name="email">
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitAddUser()">添加</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
        }

        // 提交添加用户
        async function submitAddUser() {
            const form = document.getElementById('addUserForm');
            const formData = new FormData(form);
            
            const userData = {
                username: formData.get('username'),
                password: formData.get('password'),
                realName: formData.get('realName'),
                role: formData.get('role'),
                phone: formData.get('phone'),
                email: formData.get('email')
            };
            
            try {
                Utils.showLoading();
                const response = await UserAPI.createUser(userData);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('用户添加成功', 'success');
                    closeModal();
                    loadUsers();
                } else {
                    Utils.showMessage(response.message || '添加用户失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '添加用户失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 编辑用户
        async function editUser(userId) {
            try {
                Utils.showLoading();
                const response = await UserAPI.getUserById(userId);
                
                if (response.result === 'SUCCESS') {
                    const user = response.data;
                    showModal('编辑用户', `
                        <form id="editUserForm">
                            <input type="hidden" id="editUserId" name="userId" value="${user.userId}">
                            <div class="form-group">
                                <label for="editUsername">用户名</label>
                                <input type="text" id="editUsername" name="username" value="${user.username}" required>
                            </div>
                            <div class="form-group">
                                <label for="editRealName">真实姓名</label>
                                <input type="text" id="editRealName" name="realName" value="${user.realName}" required>
                            </div>
                            <div class="form-group">
                                <label for="editRole">角色</label>
                                <select id="editRole" name="role" required>
                                    <option value="normal_user" ${user.role === 'normal_user' ? 'selected' : ''}>普通用户</option>
                                    <option value="book_admin" ${user.role === 'book_admin' ? 'selected' : ''}>图书管理员</option>
                                    <option value="system_admin" ${user.role === 'system_admin' ? 'selected' : ''}>系统管理员</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="editPhone">电话</label>
                                <input type="tel" id="editPhone" name="phone" value="${user.phone || ''}">
                            </div>
                            <div class="form-group">
                                <label for="editEmail">邮箱</label>
                                <input type="email" id="editEmail" name="email" value="${user.email || ''}">
                            </div>
                            <div class="form-group">
                                <label for="editStatus">状态</label>
                                <select id="editStatus" name="status" required>
                                    <option value="active" ${user.status === 'active' ? 'selected' : ''}>正常</option>
                                    <option value="inactive" ${user.status === 'inactive' ? 'selected' : ''}>禁用</option>
                                    <option value="pending" ${user.status === 'pending' ? 'selected' : ''}>待审核</option>
                                </select>
                            </div>
                        </form>
                    `, `
                        <button class="btn btn-primary" onclick="submitEditUser()">保存</button>
                        <button class="btn btn-secondary" onclick="closeModal()">取消</button>
                    `);
                } else {
                    Utils.showMessage(response.message || '获取用户信息失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '获取用户信息失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 提交编辑用户
        async function submitEditUser() {
            const form = document.getElementById('editUserForm');
            const formData = new FormData(form);
            
            const userData = {
                userId: parseInt(formData.get('userId')),
                username: formData.get('username'),
                realName: formData.get('realName'),
                role: formData.get('role'),
                phone: formData.get('phone'),
                email: formData.get('email'),
                status: formData.get('status')
            };
            
            // 调试信息
            console.log('提交的用户数据:', userData);
            
            try {
                Utils.showLoading();
                const response = await UserAPI.updateUser(userData);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('用户更新成功', 'success');
                    closeModal();
                    loadUsers();
                } else {
                    Utils.showMessage(response.message || '更新用户失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '更新用户失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 重置用户密码
        async function resetUserPassword(userId) {
            if (!confirm('确定要重置该用户的密码吗？')) return;
            
            try {
                Utils.showLoading();
                const response = await UserAPI.resetPassword(userId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage(`密码重置成功，新密码为：${response.data}`, 'success');
                } else {
                    Utils.showMessage(response.message || '重置密码失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '重置密码失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 删除用户
        async function deleteUser(userId) {
            if (!confirm('确定要删除该用户吗？此操作不可恢复！')) return;
            
            try {
                Utils.showLoading();
                const response = await UserAPI.deleteUser(userId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('用户删除成功', 'success');
                    loadUsers();
                } else {
                    Utils.showMessage(response.message || '删除用户失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '删除用户失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示模态框
        function showModal(title, body, footer) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalBody').innerHTML = body;
            document.getElementById('modalFooter').innerHTML = footer;
            document.getElementById('modalOverlay').classList.add('active');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.remove('active');
        }

        // 渲染分页组件
        function renderPagination(containerId, currentPage, totalPages, onPageChange) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }
            
            container.innerHTML = '';
            container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
        }

        // 渲染分页工具栏：跳页与每页条数
        function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
            const c = document.getElementById(containerId);
            if (!c) return;
            c.innerHTML = `
                <span>到第</span>
                <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
                <span>页</span>
                <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
                <span style="margin-left:12px">每页</span>
                <select id="${containerId}-size" style="width:90px">
                    <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
                    <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
                    <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
                    <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
                </select>
            `;
            const goBtn = document.getElementById(`${containerId}-go`);
            const jumpInput = document.getElementById(`${containerId}-jump`);
            const sizeSelect = document.getElementById(`${containerId}-size`);
            if (goBtn && jumpInput) {
                goBtn.onclick = () => {
                    const n = parseInt(jumpInput.value || '1', 10);
                    const page = Math.min(Math.max(1, n), totalPages);
                    onJump(page);
                };
            }
            if (sizeSelect) {
                sizeSelect.onchange = () => {
                    const size = parseInt(sizeSelect.value, 10);
                    onSizeChange(size);
                };
            }
        }
    </script>
</body>
</html>
